package com.primus.server.security.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;

public final class JwtTokenUtil {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    private static final String KEY_STORE_STR = "JKS";
    private static final String CERT_JKS = "jwt.jks";
    private static final String CERT_JKS_NAME = "jwt";
    private static final String SECRET = "primus911";
    private static InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(CERT_JKS); // 寻找证书文件
    private static PrivateKey privateKey = null;
    private static PublicKey publicKey = null;

    static { // 将证书文件里边的私钥公钥拿出来
        try {
            KeyStore keyStore = KeyStore.getInstance(KEY_STORE_STR); // java key store 固定常量
            keyStore.load(inputStream, SECRET.toCharArray());
            privateKey = (PrivateKey) keyStore.getKey(CERT_JKS_NAME, SECRET.toCharArray()); // jwt 为 命令生成整数文件时的别名
            publicKey = keyStore.getCertificate(CERT_JKS_NAME).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String generateToken(String subject) {
        return Jwts.builder()
                .setClaims(null)
                .setSubject(subject)
                // .setExpiration(new Date(System.currentTimeMillis() + expirationSeconds * 1000))
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    }

    public static String parseToken(String token) {
        String subject = null;
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(publicKey)
                    .parseClaimsJws(token).getBody();
            subject = claims.getSubject();
        } catch (Exception e) {
            System.out.println("token expired");
        }
        return subject;
    }
}
